import Vue from 'vue';
import axios from 'axios';
import util from './util';
import router from './../../router';
import qs from 'qs';
import querystring  from 'querystring';
import { Toast, Indicator, MessageBox } from 'mint-ui';

export default {

	/**
	 * 获取cookie
	 * @param {String} name 名称
	 * @param {String} value 内容
	 * @param {String} minutes 多少分钟后失效
	 */
	setCookie: function(name, value, minutes) {
		minutes = minutes || 20;
		var dateNow = new Date();
		dateNow.setMinutes(dateNow.getMinutes() + minutes);
		document.cookie = name + "=" + escape(value) + ";expires=" + dateNow.toGMTString();
	},
	/**
	 * 获取cookie
	 * @param {String} name 要获取的cookie的名称
	 */
	getCookie: function(name) {
		var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

		if(arr = document.cookie.match(reg)) return unescape(arr[2]);

		return null;
	},
	/**
	 * 清除 cookie
	 * @param {String} name 要清除的cookie的名称
	 */
	removeCookie: function(name) {
		util.setCookie(name, "", -1);
	},
	/**
	 * 获取 token
	 */
	getToken: function() {
		var token = util.getQueryString("Token");
		return token || "default";
	},
	/**
	 * 根据请求参数名称 获取请求参数值
	 * @param {String} name 参数名称
	 */
	getQueryString: function(name) { //获取浏览器参数 name为参数名
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.href.substr(window.location.href.indexOf('?') + 1);
		r = r.match(reg);
		if(r != null) return unescape(r[2]);
		return null;
	},
	/**
	 * 根据请求参数名称 获取请求参数值
	 * @param {Object} router 路由对象
	 * @param {String} path 路由名称
	 * @param {Object} queryParams 请求参数
	 */
	pushRouter: function(router, path, queryParams) { //获取浏览器参数 name为参数名
		queryParams = queryParams || {};
		if(!queryParams.Token) queryParams.Token = util.getToken();
		router.push({
			path: path,
			query: queryParams
		});
	},
	/**
	 * 去除字符串空格
	 * @param {String} str 要处理的内容
	 * @param {String} is_global 是否所有 1是 0只去除前后空格
	 */
	trimStr: function(str, is_global) {
		var result = str.replace(/(^\s+)|(\s+$)/g, "");
		if(is_global) {
			result = result.replace(/\s/g, "");
		}
		return result;
	},
	authIdCard: function(idCardNumber) {
		var re = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
		if(!re.test(idCardNumber)) {
			return true;
		} else {
			return false;
		}
	},
	isMoney: function(s) {
		var regu = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
		var re = new RegExp(regu);
		if(re.test(s)) {
			return true;
		} else {
			return false;
		}
	},
	Ajax: function(reqPath, method, paramArray, successCallBack, failuredCallBack) {
		//		var reqPath = reqPath + (reqPath.indexOf("?") == -1 ? "?" : "&") + "timeSerialize=" + (new Date()).getTime();
		//		var baseUrl = 'http://192.168.1.127', //请求地址 
		//			reqPath = baseUrl + reqPath;
		//		let Type = getMethod(reqPath, "_method");
		//
		//		function getMethod(reqPath, name) { //获取_method参数类型
		//			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		//			var r = reqPath.substr(reqPath.indexOf('?') + 1);
		//			r = r.match(reg);
		//			if(r != null) return unescape(r[2]);
		//			return "GET";
		//		}
		Indicator.open({
			text: '加载中...',
			spinnerType: 'fading-circle'
		}); //加载等待
		//打包环境
		var baseUrl = window.location.protocol + "//" + window.location.host;
		var reqUrl = baseUrl +reqPath;
		axios.defaults.baseURL = '';
		var param;
		if(method == "GET") {
			param = paramArray;
		}else{
			param = this.transformRequest(paramArray);
		}

		//测试环境
//		var reqUrl = reqPath;
//		var param;
//		if(method == "GET") {
//			param = paramArray;
//		} else {
//			param = this.transformRequest(paramArray);
//		}
		if(method == "GET") {
			axios.get(reqUrl, {
				params: param
			}).then(function(response) {
				Indicator.close();
//				console.log(response.data)
				if(JSON.stringify(response.data).indexOf("页面过期，请重新登录") != -1) {
					//所有H5网络请求失败，基本都是请求超时，提示登录失效
					MessageBox.alert('登录超时，请重新登录!').then(action => {
						util.pushRouter(router, '/kbc/h5/login'); //登录页  	
					});
				}
				successCallBack(response.data);
			}).catch(function(error) {
				Indicator.close();
//				console.log(error.response.status);
				if(error.response.status == 400 || error.response.status == 404) {
					Toast("请求失败！");
				} else {
					//所有H5网络请求失败，基本都是请求超时，提示登录失效
					MessageBox.alert('登录超时，请重新登录!').then(action => {
						util.pushRouter(router, '/kbc/h5/login'); //登录页  	
					});
				}
			});
		} else {
			axios.post(reqUrl, param, {
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
				}
			}).then(function(response) {
				Indicator.close();
				console.log(response.data)
				console.log(JSON.stringify(response.data).indexOf("页面过期，请重新登录"))
				if(JSON.stringify(response.data).indexOf("页面过期，请重新登录") != -1) {
					//所有H5网络请求失败，基本都是请求超时，提示登录失效
					MessageBox.alert('登录超时，请重新登录!').then(action => {
						util.pushRouter(router, '/kbc/h5/login'); //登录页  	
					});
				}
				successCallBack(response.data);
			}).catch(function(error) {
				Indicator.close();
				console.log(error.response.status);
				if(error.response.status == 400 || error.response.status == 404) {
					Toast("请求失败！");
				} else {
					//所有H5网络请求失败，基本都是请求超时，提示登录失效
					MessageBox.alert('登录超时，请重新登录!').then(action => {
						util.pushRouter(router, '/kbc/h5/login'); //登录页  	
					});
				}
			});
		}
	},
	upload:function(reqPath,params,successCallBack){ //跨域上传图片
		axios.post(reqPath, querystring.stringify(params), {
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
				}
			})
			.then(response => {
			  console.log(response);
			  successCallBack(response.data);
			}).catch(err => {
		 		 console.log(err);
			});
	},
	//解决java 无法接收参数
	transformRequest: function(data) {
		let ret = ''
		for(let it in data) {
			ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
		}
		return ret
	},
	/**
	 * ajax请求
	 * @param {String} reqPath 地址
	 * @param {Obj} paramArray 参数
	 * @param {function} successCallBack 成功方法
	 * @param {function} failuredCallBack 失败方法
	 */
	//	Ajax: function(reqPath, method, paramArray, successCallBack, failuredCallBack) {
	//		// reqPath = reqPath + (reqPath.indexOf("?") == -1 ? "?" : "&") + "timeSerialize=" + (new Date()).getTime();
	////		var baseUrl = window.location.protocol + "//" + window.location.host;
	//		//      var port = window.location.port;
	//		//      var baseUrl = "";
	//		//      if(port == 80){
	//		//      	baseUrl = host;
	//		//      }else{
	//		//      	baseUrl = host+":"+port;
	//		//      }
	//		//      Toast(baseUrl);
	//		//var baseUrl = 'http://localhost:8080'; //http://106.15.230.236:8888
	//		paramArray = paramArray || {};
	//		// if (!paramArray.accessToken) paramArray.accessToken =getToken();
	//		Indicator.open({
	//			text: '加载中...',
	//			spinnerType: 'fading-circle'
	//		}); //加载等待
	//		jQuery.ajax({
	//			type: method,
	//			dataType: "json",
	//			data: paramArray,
	////			url: baseUrl + reqPath,
	//			url: reqPath,
	//			success: function(data) {
	//				console.log(data);
	//				console.log(data.status);
	//				Indicator.close();
	//				if(data) {
	//					if(jQuery.isFunction(successCallBack)) {
	//						successCallBack(data);
	//					}
	//					if(jQuery.isFunction(failuredCallBack)) {
	//						failuredCallBack(data);
	//					}
	//				} else {
	//					Toast("没有获取到数据！");
	//				}
	//				//console.log(data);
	//			},
	//			error: function(data) {
	//				Indicator.close();
	//				if(data) {
	//					console.log(data);
	//					console.log(data.status);
	//					if(method.indexOf("/kbc/h5/login") > 0) { //登录页面
	//						Toast("系统错误！");
	//						return;
	//					}
	//					if(data.status == 400 || data.status == 404) {
	//						Toast("请求失败！");
	//					} else {
	//						//所有H5网络请求失败，基本都是请求超时，提示登录失效
	//						MessageBox.alert('登录超时，请重新登录!').then(action => {
	//							util.pushRouter(router, '/kbc/h5/login'); //登录页  	
	//						});
	//					}
	//				} else {
	//					Toast(data.status + "错误!");
	//				}
	//			}
	//		});
	//	},
	returnFloat: function(value) {
		var value = Math.round(parseFloat(value) * 100) / 100;
		var xsd = value.toString().split(".");
		if(xsd.length == 1) {
			value = value.toString() + ".00";
			return value;
		}
		if(xsd.length > 1) {
			if(xsd[1].length < 2) {
				value = value.toString() + "0";
			}
			return value;
		}
	},
	/**
	 * 根据 PLAY_LANG 属性来获取浏览器的语言
	 * @param {Object} name --PLAY_LANG 属性
	 * @param {Object} defaultValue --默认语言,例如'zh'
	 */
	getLangByCookie: function(name, defaultValue) {
		var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
		if(arr = document.cookie.match(reg))
			return unescape(arr[2]);
		else
			return defaultValue;
	},
	isEmpty: function(str) {
		if(str == "" || str == "null" || str == "undefined" || str == null || str == undefined) {
			return true;
		} else {
			return false;
		}
	},
	/*
	 * 邮箱检查
	 */
	CheckMail: function(mail) {
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if(filter.test(mail)) return true;
		else {
			return false;
		}
	},
	/*
	 * 验证电话号码
	 */
	CheckTel: function(tel) {
		var bValidate = RegExp(/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/).test(tel);
		if(bValidate) {
			return true;
		} else {
			return false;
		}
	},
	getSessionLocation: function(callback) { //高德浏览器定位城市
		var $this = this;
		var locationCookieKey = 'location';
		var location = $this.getCookie(locationCookieKey);
		if(location) {
			location = JSON.parse(location);
			callback(location); //返回城市信息
		} else {
			var geolocation = new AMap.Geolocation({
				resizeEnable: true,
				enableHighAccuracy: true, //是否使用高精度定位，默认:true
				timeout: 10000 //超过10秒后停止定位，默认：无穷大
			});
			geolocation.getCurrentPosition(); //浏览器定位
			AMap.event.addListener(geolocation, 'complete', function(data) {
				var Longitude = data.position.getLng();
				var Latitude = data.position.getLat();
				var geocoder = new AMap.Geocoder();
				var lnglatXY = [Longitude, Latitude]
				geocoder.getAddress(lnglatXY, function(status, result) {
					if(status === 'complete' && result.info === 'OK') {
						var _city = result.regeocode.addressComponent.city;
						var _district = result.regeocode.addressComponent.district;
						var _province = result.regeocode.addressComponent.province;
						var _street = result.regeocode.addressComponent.street;
						var _streetNumber = result.regeocode.addressComponent.streetNumber;
						var _township = result.regeocode.addressComponent.township;
						var _address = _province + _city + _street + _township + _streetNumber;
						var _adcode = result.regeocode.addressComponent.adcode;
						location = {
							"provinceCode": _adcode.substring(0, 2) + '0000',
							"cityCode": '', //_adcode.substring(0, 4) + '00'
							"cityCodeId": _adcode.substring(0, 4) + '00',
							"adcode": _adcode,
							"province": _province,
							"city": _city,
							"district": _district,
							"Longitude": Longitude,
							"Latitude": Latitude,
							"address": _address
						};
						$this.setCookie(locationCookieKey, JSON.stringify(location), 1);
						callback(location); //返回城市信息
					}
				});
			})
			//定位失败返回贵阳市
			AMap.event.addListener(geolocation, 'error', function(data) {
				location = {
					"adcode": "520113",
					"cityCode": '', //520100
					"cityCodeId": '520100',
					"provinceCode": '520000',
					"city": '贵阳市',
					"province": '贵州省',
					"Longitude": 106.692152,
					"Latitude": 26.58156,
					"address": '贵州省贵阳市云岩区'
				};
				callback(location); //返回城市信息
			});
		}
	},
	payTyeName: function(typeNo) {
		var typeName;
		switch(typeNo) {
			case "101":
				typeName = "总钱包转出";
				break;
			case "102":
				typeName = "总钱包收入";
				break;
			case "103":
				typeName = "生息钱包转出";
				break;
			case "104":
				typeName = "生息钱包收入";
				break;
			case "105":
				typeName = "奖励钱包转出";
				break;
			case "106":
				typeName = "奖励钱包收入";
				break;
			case "107":
				typeName = "KBC私幕钱包转入";
				break;
			case "201":
				typeName = "总钱包转生息钱包";
				break;
			case "202":
				typeName = "总钱包转奖励钱包";
				break;
			case "203":
				typeName = "生息钱包转总钱包";
				break;
			case "204":
				typeName = "生息钱包转奖励钱包";
				break;
			case "205":
				typeName = "奖励钱包转总钱包";
				break;
			case "206":
				typeName = "奖励钱包转生息钱包";
				break;
			case "301":
				typeName = "普通日息";
				break;
			case "302":
				typeName = "锁仓日息";
				break;
			case "303":
				typeName = "业绩奖励";
				break;
			case "304":
				typeName = "懒人奖励";
				break;
			case "305":
				typeName = "领导奖";
				break;
			case "401":
				typeName = "出售";
				break;
			case "402":
				typeName = "购买";
				break;
			case "501":
				typeName = "首次充值";
				break;
			case "502":
				typeName = "普通充值";
				break;
			case "503":
				typeName = "扣款";
				break;
			case "999":
				typeName = "其他";
				break;
			default:
				typeName = "其他";
				break;
		}
		return typeName;

	},
	getMemberName: function(typeNo) {
		var memberName;
		switch(typeNo) {
			case "1":
				memberName = "一星会员";
				break;
			case "2":
				memberName = "二星会员";
				break;
			case "3":
				memberName = "三星会员";
				break;
			case "4":
				memberName = "四星会员";
				break;
			case "5":
				memberName = "五星会员";
				break;
			case "11":
				memberName = "白金会员";
				break;
			case "12":
				memberName = "铂金会员";
				break;
			case "13":
				memberName = "砖石会员";
				break;
			default:
				memberName = "非会员";
				break;
		}
		return memberName;

	},
	DrivingFunction: function(longitude, latitude, shopLongitude, shopLatitude) { //规划导航路线
		//创建驾车路线规划组件
		var driving = new AMap.Driving({
			hideMarkers: true
		});
		//console.log(shopLongitude+"==="+shopLatitude+"=="+longitude+"===="+latitude);
		//根据起终点坐标规划驾车路线[116.379028, 39.865042], [116.427281, 39.903719],
		driving.search([longitude, latitude], [shopLongitude, shopLatitude], function(status, result) {
			driving.searchOnAMAP({
				origin: result.origin,
				destination: result.destination
			});
		})
	},
	VueLazyload: function() {
		//图片赖加载
		Vue.use(VueLazyload, {
			preLoad: 1.3,
			error: require("./../../assets/bj_logo.png"),
			loading: require("./../../assets/bj_loading.gif"),
			attempt: 1
		})
	},

	//创建AJAX异步对象，即XMLHttpRequest  
	createAJAX: function() {
		var ajax = null;
		try {
			ajax = new ActiveXObject("microsoft.xmlhttp");
		} catch(e1) {
			try {
				ajax = new XMLHttpRequest();
			} catch(e2) {
				alert("你的浏览器不支持ajax，请更换浏览器");
			}
		}
		return ajax;
	}
}